<?php

namespace app\zyhsapi\controller\v3;

use app\common\cachemodel\ZlRecommendDivination;
use app\common\lib\exception\ApiException;
use app\common\lib\tarot\Tarot;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\lib\ZyhsDivinationLib;
use app\zyhsapi\model\ZyhsDivination;
use app\zyhsapi\model\ZyhsTarotRecords;
use think\Log;
use think\response\Json;

class Divination extends ZyhsAuth
{
    /**
     * 获取 塔罗｜骰子 推荐问题
     * @return Json
     */
    public function getRecommendQuestion()
    {
        $type = input('type/d', 1); // 1=>骰子问题 2=>塔罗问题

        $recommendList = (new ZlRecommendDivination())->getRecommendQuestion($type, 2);

        $resDAta = [
            'recommend_list' => $recommendList,
        ];
        if ($type === 1)
        {
            $resDAta['img'] = '/test/tarot/divination1.png';
            $resDAta['title'] = '骰子提问';
        } elseif ($type === 2)
        {
            $resDAta['img'] = '/test/tarot/divination2v2.png';
            $resDAta['title'] = '三牌塔罗提问';
        }

        return show(config('code.success'), '请求成功', $resDAta);
    }

    /**
     * 开始 骰子占卜
     * @return Json
     */
    public function start()
    {
        $data['question'] = htmlspecialchars(trim(input('question')));
        $data['uid'] = $this->user['id'];
        $data['timezone'] = input('timezone');// 时区
        $data['longitude'] = input('longitude');// 经度
        $data['latitude'] = input('latitude');// 纬度
        $validate = validate('DivinationIndex');
        if ($validate->check($data) !== true)
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $_arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 16];// 行星id随机数种子

        $data['planet'] = $_arr[rand(0, count($_arr) - 1)];
        $data['sign'] = rand(1, 12);
        $data['house'] = rand(1, 12);
        $data['deg'] = round(randomFloat(0, 29), 8);
        $data['create_time'] = time();

        try
        {
            $zyhsDivinationModel = new ZyhsDivination();
            $id = $zyhsDivinationModel->saveData($this->user['id'], $data);
        }
        catch (\Exception $e)
        {
            Log::write('提问入库失败:' . $e->getMessage(), 'divination_error', true);
            return show(config('code.error'), '请稍后重试');
        }

        return show(config('code.success'), '加载成功', ['did' => (int)($id), 'time' => $data['create_time']]);
    }

    /**
     * 提问 历史记录
     * @return Json
     * @throws \Exception
     */
    public function dataList()
    {
        $uid = $this->user['id'];
        $type = input('type/d', 1);
        $page = input('page/d', 1);
        if (!in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if ($type === 2)
        {
            $model = new ZyhsTarotRecords();
        } else
        {
            $model = new ZyhsDivination();
        }

        $data = $model->getListPage($uid);

        $data['data'] = $model->pageDataReset($data['data']);
        $data['tabs'] = null;

        if ($page === 1)
        {
            $data['tabs'] = [
                [
                    'type' => 1,
                    'name' => '占星骰子',
                    'is_select' => $type === 1 ? 1 : 0,
                ], [
                    'type' => 2,
                    'name' => '塔罗占卜',
                    'is_select' => $type === 2 ? 1 : 0,
                ],
            ];
        }

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 骰子经典模式
     * @return Json
     * @throws \Exception
     */
    public function diceInfo()
    {
        $did = input('did/d', 0);
        if (!$did)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zyhsDivinationModel = new ZyhsDivination();

        $detail = $zyhsDivinationModel->getInfoById($did);

        if (!$detail || $detail['uid'] !== $this->user['id'] || $detail['is_del'])
        {
            return show(config('code.error'), '数据不存在');
        }

        $result = (new ZyhsDivinationLib())->getDiceInfo($detail);

        return show(config('code.success'), '加载成功', $result);
    }

    /**
     * 专业模式
     * @return Json
     */
    public function specialtyInfo()
    {
        $did = input('did/d', 0);
        if (!$did)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $zyhsDivinationModel = new ZyhsDivination();

        $detail = $zyhsDivinationModel->getInfoById($did);
        if (!$detail || $detail['uid'] !== $this->user['id'] || $detail['is_del'])
        {
            return show(config('code.error'), '数据不存在');
        }

        $details = (new ZyhsDivinationLib())->specialtyInfo($detail);

        return show(config('code.success'), '成功', $details);
    }


    /**
     * 卜卦模式
     * @return Json
     */
    public function divinationInfo()
    {
        $did = input('did/d', 0);
        if (!$did)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $tid = input('tid/d', 1);
        // 星盘配置方案使用默认值
        if (!in_array($tid, [1, 2, 3], true))
        {
            $tid = 1;
        }
        $zyhsDivinationModel = new ZyhsDivination();
        $detail = $zyhsDivinationModel->getInfoById($did);
        if (!$detail || $detail['uid'] !== $this->user['id'] || $detail['is_del'])
        {
            return show(config('code.error'), '数据不存在');
        }

        $data = (new ZyhsDivinationLib())->getDivinationInfo($detail, $tid);

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 删除 占卜记录
     * @return Json
     * @throws \Exception
     */
    public function del()
    {
        $type = input('type/d', 1);
        $did = input('did/d', 0);
        if (!in_array($type, [1, 2], true) || !$did)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if ($type === 2)
        {
            $model = new ZyhsTarotRecords();
        } else
        {
            $model = new ZyhsDivination();
        }

        $detail = $model->getInfoById($did);

        if (!$detail || $detail['uid'] !== $this->user['id'] || $detail['is_del'])
        {
            return show(config('code.success'), '删除成功');
        }

        $res = $model->delData($this->user['id'], $did);

        if ($res)
        {
            return show(config('code.success'), '删除成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 塔罗 开始占卜
     * @return Json
     * @throws ApiException
     */
    public function tarotAdd()
    {
        $type = input('type/d', 2); // 2 自定义提问（免费）  1 推荐提问
        $question = htmlspecialchars(trim(input('question/s', '')));
        $id = input('id/d', 0);

        if ($type === 2)
        {   // 自定义问题
            if (!$question)
            {
                return show(config('code.error'), '请输入问题，再进行占卜');
            }

            if (mb_strlen($question) > 30)
            {
                return show(config('code.error'), '提问最多30字，占卜失败');
            }

            $tarotType = 1; // 自定义问题 1号牌阵 （免费）
            $gid = 0;
            $status = 1; // 1解锁 0未解锁
        } else
        {   // 获取推荐占卜信息 内的牌阵信息
            if (!$id)
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
            $recommendTarotInfo = (new ZlRecommendDivination())->getInfoById($id, ['question', 'tarot_type', 'gid']);
            if (!$recommendTarotInfo)
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
            $question = $recommendTarotInfo['question'];
            $tarotType = (int)$recommendTarotInfo['tarot_type'];
            $gid = (int)$recommendTarotInfo['gid'];
            $status = 0; // 1解锁 0未解锁
        }

        // 获取塔罗占卜结果
        $tarotData = (new Tarot())->getTarot($tarotType);
        $data = [
            'uid' => $this->user['id'],
            'question' => $question,
            'type' => $type,
            'gid' => $gid,
            'status' => $status,
            'tarot_type' => $tarotType,
            'content' => json_encode($tarotData, JSON_UNESCAPED_UNICODE),
            'create_time' => $this->request->time(),
        ];
        $tarotRecordModel = new ZyhsTarotRecords();

        $tarotId = $tarotRecordModel->saveData($this->user['id'], $data);

        if ($tarotId)
        {
            $tarotRecordModel->divinationNumAdd($tarotType); // 占卜数量增加
            return show(config('code.success'), '占卜成功', ['tarot_id' => (int)$tarotId]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 获取 塔罗占卜详情
     * @return Json
     * @throws \Exception
     */
    public function getTarotDetail()
    {
        $tarotId = input('tarot_id/d', 0);

        if (!$tarotId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $tarotRecordModel = new ZyhsTarotRecords();
        // 获取占卜信息
        $tarotInfo = $tarotRecordModel->getInfoById($tarotId, ['id', 'uid', 'gid', 'status', 'tarot_type', 'content', 'question', 'create_time']);

        if (!$tarotInfo || $this->user['id'] !== (int)$tarotInfo['uid'])
        {
            return show(config('code.error'), '服务异常，占卜记录不存在');
        }

        // 获取详情返回结果信息
        $resData = $tarotRecordModel->getDetails($tarotInfo);

        return show(config('code.success'), '请求成功', $resData);
    }
}